package com.hzyl.famousreader.repository.webservice;

import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.hzyl.famousreader.BuildConfig;
import com.hzyl.famousreader.repository.webservice.cache.LiveDataCallAdapterFactory;
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import java.util.concurrent.TimeUnit;

/**
 * Created by goldze on 2017/5/10.
 * RetrofitClient封装单例类, 实现网络请求
 */
public class RetrofitClient {

  //服务器地址
//  private static final String BASE_URL = "http://www.weishitianli.com/famous/";
  private static final String BASE_URL = "http://120.79.101.71:8090/";
  //private static final String BASE_URL_DEBUG = "http://www.weishitianli.com/famous/";
  private static final String BASE_URL_DEBUG = "http://120.79.101.71:8090/";

  //超时时间
  private static final int DEFAULT_TIMEOUT = 20;
  //缓存时间
  private static final int CACHE_TIMEOUT = 10 * 1024 * 1024;

  private static Retrofit INSTANCE;

  private RetrofitClient() {
  }

  public static Retrofit getInstance() {
    if (INSTANCE == null) {
      synchronized (RetrofitClient.class) {
        if (INSTANCE == null) {

          HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
          loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

          OkHttpClient okHttpClient = new OkHttpClient.Builder()
            .addInterceptor(loggingInterceptor)
            .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS)
            .connectionPool(new ConnectionPool(8, 15, TimeUnit.SECONDS))
            .build();

          //设置驼峰转换
          Gson gson = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .create();

          INSTANCE = new Retrofit.Builder()
            .baseUrl(BuildConfig.DEBUG ? BASE_URL_DEBUG : BASE_URL)
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(new LiveDataCallAdapterFactory())
            .build();
        }
      }
    }
    return INSTANCE;
  }
}
